export let name = "productCategory";

export function render() {
    return `
     <style>
         .container {
             max-width: 1200px;
             margin: 0 auto;
             background-color: #fff;
             border-radius: 8px;
             box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
             padding: 20px;
             max-height: 90vh;
             overflow: hidden;
         }
         .header {
             display: flex;
             justify-content: space-between;
             align-items: center;
             margin-bottom: 20px;
             padding-bottom: 20px;
             border-bottom: 1px solid #eee;
         }

         .title {
             font-size: 24px;
             color: #333;
         }

         .toolbar {
             display: flex;
             gap: 10px;
         }

         .search-box {
             position: relative;
         }

         .search-box input {
             padding: 8px 35px 8px 15px;
             border: 1px solid #ddd;
             border-radius: 4px;
             width: 250px;
         }

         .search-box::after {
             content: "🔍";
             position: absolute;
             right: 10px;
             top: 50%;
             transform: translateY(-50%);
         }

         .btn {
             padding: 8px 16px;
             border: none;
             border-radius: 4px;
             cursor: pointer;
             transition: background-color 0.3s;
         }

         .btn-primary {
             background-color: #7438d5;
             color: white;
            
         }

         .btn-primary:hover {
             background-color: #5d2bb0;
         }

         .btn-success {
             background-color: #1b44e3;
             color: white;
         }

         .btn-success:hover {
             background-color: #1fd0c2;
         }

         .btn-warning {
             background-color: #ff9800;
             color: white;
         }

         .btn-warning:hover {
             background-color: #e68900;
         }

         table {
             width: 100%;
             border-collapse: collapse;
             margin-bottom: 20px;
         }

         th, td {
             padding: 12px 15px;
             text-align: left;
             border-bottom: 1px solid #ddd;
         }

         th {
             background-color: #f2f2f2;
             font-weight: bold;
             position: sticky;
             top: 0;
             z-index: 10;
         }

         tr:hover {
             background-color: #f5f5f5;
         }

         .badge {
             padding: 4px 8px;
             border-radius: 4px;
             font-size: 12px;
             font-weight: bold;
         }

         .badge-success {
             background-color: #dff0d8;
             color: #3c763d;
         }

         .badge-warning {
             background-color: #fcf8e3;
             color: #8a6d3b;
         }

         .badge-danger {
             background-color: #f2dede;
             color: #a94442;
         }

         .action-btn {
             padding: 6px 12px;
             margin-right: 5px;
             border: none;
             border-radius: 4px;
             cursor: pointer;
             transition: background-color 0.3s;
         }

         .action-btn.edit {
             background-color: #000000;
             color: #ffffff;
         }

         .action-btn.edit:hover {
             background-color: #969292;
         }

         .action-btn.delete {
             background-color: #1a1919;
             color: #ffffff;
         }

         .action-btn.delete:hover {
             background-color: #969292;
         }

         .action-btn.stock {
             background-color: #4CAF50;
             color: #ffffff;
         }

         .action-btn.stock:hover {
             background-color: #45a049;
         }

         .pagination {
             display: flex;
             justify-content: center;
             align-items: center;
             gap: 5px;
             padding: 10px 0;
         }

         .pagination-btn {
             padding: 8px 12px;
             border: 1px solid #ddd;
             background-color: white;
             cursor: pointer;
             border-radius: 4px;
         }

         .pagination-btn.active {
             background-color: #7438d5;
             color: white;
             border-color: #7438d5;
         }

         .pagination-btn:disabled {
             opacity: 0.5;
             cursor: not-allowed;
         }

         .modal {
             display: none;
             position: fixed;
             z-index: 1000;
             left: 0;
             top: 0;
             width: 100%;
             height: 100%;
             background-color: rgba(0,0,0,0.4);
         }

         .modal-content {
             background-color: #fefefe;
             margin: 10% auto;
             padding: 20px;
             border: 1px solid #888;
             width: 50%;
             max-width: 600px;
             border-radius: 8px;
             box-shadow: 0 4px 8px rgba(0,0,0,0.1);
         }

         .modal-header {
             display: flex;
             justify-content: space-between;
             align-items: center;
             margin-bottom: 20px;
             padding-bottom: 10px;
             border-bottom: 1px solid #eee;
         }

         .modal-title {
             font-size: 20px;
             font-weight: bold;
         }

         .close {
             color: #aaa;
             font-size: 28px;
             font-weight: bold;
             cursor: pointer;
         }

         .close:hover {
             color: black;
         }

         .form-group {
             margin-bottom: 15px;
         }

         .form-group label {
             display: block;
             margin-bottom: 5px;
             font-weight: bold;
         }

         .form-control {
             width: 100%;
             padding: 10px;
             border: 1px solid #ddd;
             border-radius: 4px;
             box-sizing: border-box;
         }

         .form-actions {
             display: flex;
             justify-content: flex-end;
             gap: 10px;
             margin-top: 20px;
         }

         .alert {
             padding: 15px;
             margin-bottom: 20px;
             border-radius: 4px;
         }

         .alert-success {
             background-color: #dff0d8;
             color: #3c763d;
         }

         .no-data {
             text-align: center;
             padding: 20px;
             color: #777;
         }
         
         /* 表格滚动容器样式 - 增强版 */
         #inventoryTableContainer {
             max-height: calc(90vh - 180px);
             overflow-y: auto;
             margin-bottom: 20px;
             border: 1px solid #eee;
             border-radius: 4px;
             scroll-behavior: smooth; /* 平滑滚动 */
         }
         
         /* 自定义滚动条样式 - 增强版 */
         #inventoryTableContainer::-webkit-scrollbar {
             width: 10px;
             height: 10px;
         }
         
         #inventoryTableContainer::-webkit-scrollbar-track {
             background: #f1f1f1;
             border-radius: 6px;
         }
         
         #inventoryTableContainer::-webkit-scrollbar-thumb {
             background: #bbb;
             border-radius: 6px;
             border: 2px solid #f1f1f1;
         }
         
         #inventoryTableContainer::-webkit-scrollbar-thumb:hover {
             background: #999;
         }
         
         #inventoryTableContainer::-webkit-scrollbar-thumb:active {
             background: #777;
         }
         
         /* 滚动条角落样式 */
         #inventoryTableContainer::-webkit-scrollbar-corner {
             background: #f1f1f1;
             border-radius: 0 0 6px 0;
         }
     </style>

     <div class="container">
        <div class="header">
            <h1 class="title">库存管理</h1>
            <div class="toolbar">
                <div class="search-box">
                    <input type="text" id="searchInput" placeholder="搜索产品...">
                </div>
                <button class="btn btn-success" id="addProductBtn">添加产品</button>
                <button class="btn btn-warning" id="lowStockBtn">低库存预警</button>
            </div>
        </div>

        <!-- 带增强滚动功能的表格容器 -->
        <div id="inventoryTableContainer">
            <table id="inventoryTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>产品名称</th>
                        <th>类别</th>
                        <th>价格</th>
                        <th>库存数量</th>
                        <th>库存状态</th>
                        <th>仓库位置</th>
                        <th>最后更新</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="inventoryTableBody">
                    <!-- 库存数据将通过JavaScript动态生成 -->
                </tbody>
            </table>
            <div id="noDataMessage" class="no-data" style="display: none;">没有找到库存数据</div>
        </div>

        <div class="pagination" id="pagination">
            <!-- 分页按钮将通过JavaScript动态生成 -->
        </div>
     </div>

     <!-- 添加/编辑产品的模态框 -->
     <div id="productModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="modalTitle">添加产品</h2>
                <span class="close">&times;</span>
            </div>
            <form id="productForm">
                <input type="hidden" id="productId">
                <div class="form-group">
                    <label for="productName">产品名称</label>
                    <input type="text" class="form-control" id="productName" required>
                </div>
                <div class="form-group">
                    <label for="productCategory">产品类别</label>
                    <select class="form-control" id="productCategory" required>
                        <option value="">请选择类别</option>
                        <option value="电子产品">电子产品</option>
                        <option value="家居用品">家居用品</option>
                        <option value="服装">服装</option>
                        <option value="食品">食品</option>
                        <option value="图书">图书</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="productPrice">价格</label>
                    <input type="number" class="form-control" id="productPrice" min="0" step="0.01" required>
                </div>
                <div class="form-group">
                    <label for="productQuantity">库存数量</label>
                    <input type="number" class="form-control" id="productQuantity" min="0" step="1" required>
                </div>
                <div class="form-group">
                    <label for="warehouseLocation">仓库位置</label>
                    <input type="text" class="form-control" id="warehouseLocation" placeholder="例如：A区-12架-05层" required>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" id="cancelBtn">取消</button>
                    <button type="submit" class="btn btn-primary" id="saveBtn">保存</button>
                </div>
            </form>
        </div>
     </div>

     <!-- 库存调整模态框 -->
     <div id="stockAdjustModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">调整库存</h2>
                <span class="close">&times;</span>
            </div>
            <form id="stockAdjustForm">
                <input type="hidden" id="adjustProductId">
                <div class="form-group">
                    <label for="currentStock">当前库存</label>
                    <input type="number" class="form-control" id="currentStock" readonly>
                </div>
                <div class="form-group">
                    <label for="adjustType">调整类型</label>
                    <select class="form-control" id="adjustType" required>
                        <option value="increase">入库</option>
                        <option value="decrease">出库</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="adjustQuantity">调整数量</label>
                    <input type="number" class="form-control" id="adjustQuantity" min="1" step="1" required>
                </div>
                <div class="form-group">
                    <label for="adjustReason">调整原因</label>
                    <textarea class="form-control" id="adjustReason" rows="3" required></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" id="cancelAdjustBtn">取消</button>
                    <button type="submit" class="btn btn-primary" id="confirmAdjustBtn">确认调整</button>
                </div>
            </form>
        </div>
     </div>

     <!-- 通知提示 -->
     <div id="notification" class="alert alert-success" style="display: none; position: fixed; top: 20px; right: 20px; z-index: 1050;"></div>
    `;
}

export function afterRender() {
    // 本地存储键名
    var STORAGE_KEY = 'inventoryData';
    const LOW_STOCK_THRESHOLD = 10; // 低库存阈值

    // 获取DOM元素
    var inventoryTableBody = document.getElementById('inventoryTableBody');
    var noDataMessage = document.getElementById('noDataMessage');
    var searchInput = document.getElementById('searchInput');
    var addProductBtn = document.getElementById('addProductBtn');
    var lowStockBtn = document.getElementById('lowStockBtn');
    var modal = document.getElementById('productModal');
    var stockAdjustModal = document.getElementById('stockAdjustModal');
    var modalTitle = document.getElementById('modalTitle');
    var productForm = document.getElementById('productForm');
    var stockAdjustForm = document.getElementById('stockAdjustForm');
    var productIdInput = document.getElementById('productId');
    var adjustProductIdInput = document.getElementById('adjustProductId');
    var productNameInput = document.getElementById('productName');
    var productCategoryInput = document.getElementById('productCategory');
    var productPriceInput = document.getElementById('productPrice');
    var productQuantityInput = document.getElementById('productQuantity');
    var warehouseLocationInput = document.getElementById('warehouseLocation');
    var currentStockInput = document.getElementById('currentStock');
    var adjustTypeInput = document.getElementById('adjustType');
    var adjustQuantityInput = document.getElementById('adjustQuantity');
    var adjustReasonInput = document.getElementById('adjustReason');
    var cancelBtn = document.getElementById('cancelBtn');
    var cancelAdjustBtn = document.getElementById('cancelAdjustBtn');
    var closeBtns = document.querySelectorAll('.close');
    var notification = document.getElementById('notification');
    var pagination = document.getElementById('pagination');

    // 分页相关变量
    let currentPage = 1;
    const itemsPerPage = 8; // 每页显示更多数据，更好地展示滚动效果
    let filteredProducts = [];
    let allProducts = [];

    // 初始化
    init();

    // 初始化函数
    function init() {
        // 从本地存储加载数据
        loadProducts();

        // 渲染库存表格
        renderInventoryTable();

        // 设置事件监听器
        setupEventListeners();
    }

    // 从本地存储加载产品数据，并按ID升序排序
    function loadProducts() {
        var storedData = localStorage.getItem(STORAGE_KEY);
        if (storedData) {
            allProducts = JSON.parse(storedData);
        } else {
            // 默认示例数据
            allProducts = [
                {
                    id: 1,
                    name: "iPhone 13",
                    category: "电子产品",
                    price: 5999,
                    quantity: 25,
                    warehouseLocation: "A区-01架-03层",
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 2,
                    name: "小米电视5",
                    category: "电子产品",
                    price: 3299,
                    quantity: 12,
                    warehouseLocation: "A区-05架-02层",
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 3,
                    name: "华为MateBook 14",
                    category: "电子产品",
                    price: 5699,
                    quantity: 8,
                    warehouseLocation: "A区-03架-01层",
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 4,
                    name: "欧式沙发",
                    category: "家居用品",
                    price: 2599,
                    quantity: 3,
                    warehouseLocation: "B区-12架-01层",
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 5,
                    name: "纯棉四件套",
                    category: "家居用品",
                    price: 399,
                    quantity: 45,
                    warehouseLocation: "B区-08架-04层",
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 6,
                    name: "牛仔裤",
                    category: "服装",
                    price: 199,
                    quantity: 78,
                    warehouseLocation: "C区-03架-02层",
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 7,
                    name: "休闲T恤",
                    category: "服装",
                    price: 99,
                    quantity: 120,
                    warehouseLocation: "C区-01架-05层",
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 8,
                    name: "巧克力",
                    category: "食品",
                    price: 29.9,
                    quantity: 5,
                    warehouseLocation: "D区-05架-01层",
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 9,
                    name: "笔记本电脑",
                    category: "电子产品",
                    price: 4599,
                    quantity: 15,
                    warehouseLocation: "A区-02架-03层",
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 10,
                    name: "运动鞋",
                    category: "服装",
                    price: 399,
                    quantity: 67,
                    warehouseLocation: "C区-06架-02层",
                    updatedAt: new Date().toISOString()
                }
            ];
            saveProducts();
        }

        // 初始化过滤后的产品列表
        filteredProducts = [...allProducts];
        // 按ID升序排序
        filteredProducts.sort((a, b) => a.id - b.id);
    }

    // 保存产品数据到本地存储
    function saveProducts() {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(allProducts));
    }

    // 渲染库存表格
    function renderInventoryTable() {
        // 清空表格
        inventoryTableBody.innerHTML = '';

        // 获取当前页数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = Math.min(startIndex + itemsPerPage, filteredProducts.length);
        const currentProducts = filteredProducts.slice(startIndex, endIndex);

        // 如果没有数据，显示提示信息
        if (currentProducts.length === 0) {
            noDataMessage.style.display = 'block';
            inventoryTableBody.style.display = 'none';
        } else {
            noDataMessage.style.display = 'none';
            inventoryTableBody.style.display = 'table-row-group';

            // 渲染产品行
            currentProducts.forEach(product => {
                // 确定库存状态
                let stockStatus, badgeClass;
                if (product.quantity === 0) {
                    stockStatus = '缺货';
                    badgeClass = 'badge-danger';
                } else if (product.quantity <= LOW_STOCK_THRESHOLD) {
                    stockStatus = '低库存';
                    badgeClass = 'badge-warning';
                } else {
                    stockStatus = '正常';
                    badgeClass = 'badge-success';
                }

                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${product.id}</td>
                    <td>${product.name}</td>
                    <td>${product.category}</td>
                    <td>¥${product.price.toFixed(2)}</td>
                    <td>${product.quantity}</td>
                    <td><span class="badge ${badgeClass}">${stockStatus}</span></td>
                    <td>${product.warehouseLocation}</td>
                    <td>${new Date(product.updatedAt).toLocaleString()}</td>
                    <td>
                        <button class="action-btn edit" data-id="${product.id}">编辑</button>
                        <button class="action-btn stock" data-id="${product.id}">调整库存</button>
                        <button class="action-btn delete" data-id="${product.id}">删除</button>
                    </td>
                `;
                inventoryTableBody.appendChild(row);
            });
        }

        // 渲染分页
        renderPagination();
    }

    // 渲染分页
    function renderPagination() {
        pagination.innerHTML = '';

        const totalPages = Math.ceil(filteredProducts.length / itemsPerPage);

        if (totalPages <= 1) return;

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.className = 'pagination-btn';
        prevBtn.textContent = '上一页';
        prevBtn.disabled = currentPage === 1;
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                renderInventoryTable();
                scrollToTop(); // 滚动到顶部
            }
        });
        pagination.appendChild(prevBtn);

        // 页码按钮 - 只显示当前页附近的页码
        const pageRange = 2; // 当前页前后显示的页码数量
        let startPage = Math.max(1, currentPage - pageRange);
        let endPage = Math.min(totalPages, currentPage + pageRange);

        // 确保显示第一页和最后一页
        if (startPage > 1) {
            addPageButton(1);
            if (startPage > 2) addEllipsis();
        }

        // 添加中间页码
        for (let i = startPage; i <= endPage; i++) {
            addPageButton(i);
        }

        // 确保显示最后一页
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) addEllipsis();
            addPageButton(totalPages);
        }

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.className = 'pagination-btn';
        nextBtn.textContent = '下一页';
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                currentPage++;
                renderInventoryTable();
                scrollToTop(); // 滚动到顶部
            }
        });
        pagination.appendChild(nextBtn);

        // 添加页码按钮的辅助函数
        function addPageButton(pageNum) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `pagination-btn ${pageNum === currentPage ? 'active' : ''}`;
            pageBtn.textContent = pageNum;
            pageBtn.addEventListener('click', () => {
                currentPage = pageNum;
                renderInventoryTable();
                scrollToTop(); // 滚动到顶部
            });
            pagination.appendChild(pageBtn);
        }

        // 添加省略号的辅助函数
        function addEllipsis() {
            const ellipsis = document.createElement('span');
            ellipsis.className = 'pagination-ellipsis';
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 5px';
            pagination.appendChild(ellipsis);
        }
    }

    // 滚动到表格容器顶部
    function scrollToTop() {
        const tableContainer = document.getElementById('inventoryTableContainer');
        tableContainer.scrollTop = 0;
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 搜索功能
        searchInput.addEventListener('input', handleSearch);

        // 添加产品按钮
        addProductBtn.addEventListener('click', openAddModal);

        // 低库存预警按钮
        lowStockBtn.addEventListener('click', showLowStockItems);

        // 编辑、删除和调整库存按钮（委托事件）
        inventoryTableBody.addEventListener('click', function(e) {
            if (e.target.classList.contains('edit')) {
                const productId = parseInt(e.target.getAttribute('data-id'));
                openEditModal(productId);
            }

            if (e.target.classList.contains('delete')) {
                const productId = parseInt(e.target.getAttribute('data-id'));
                deleteProduct(productId);
            }

            if (e.target.classList.contains('stock')) {
                const productId = parseInt(e.target.getAttribute('data-id'));
                openStockAdjustModal(productId);
            }
        });

        // 模态框关闭按钮
        closeBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                modal.style.display = 'none';
                stockAdjustModal.style.display = 'none';
            });
        });

        // 取消按钮
        cancelBtn.addEventListener('click', () => modal.style.display = 'none');
        cancelAdjustBtn.addEventListener('click', () => stockAdjustModal.style.display = 'none');

        // 点击模态框外部关闭
        window.addEventListener('click', function(e) {
            if (e.target === modal) modal.style.display = 'none';
            if (e.target === stockAdjustModal) stockAdjustModal.style.display = 'none';
        });

        // 表单提交
        productForm.addEventListener('submit', function(e) {
            e.preventDefault();
            saveProduct();
        });

        stockAdjustForm.addEventListener('submit', function(e) {
            e.preventDefault();
            adjustStock();
        });
    }

    // 处理搜索
    function handleSearch() {
        const keyword = searchInput.value.trim().toLowerCase();

        if (keyword) {
            filteredProducts = allProducts.filter(product =>
                product.id.toString().includes(keyword) ||
                product.name.toLowerCase().includes(keyword) ||
                product.category.toLowerCase().includes(keyword) ||
                product.warehouseLocation.toLowerCase().includes(keyword)
            );
        } else {
            // 重置为所有产品
            filteredProducts = [...allProducts];
        }

        // 搜索后仍然保持ID升序
        filteredProducts.sort((a, b) => a.id - b.id);

        currentPage = 1;
        renderInventoryTable();
    }

    // 显示低库存商品
    function showLowStockItems() {
        filteredProducts = allProducts.filter(product => product.quantity > 0 && product.quantity <= LOW_STOCK_THRESHOLD);
        filteredProducts.sort((a, b) => a.quantity - b.quantity); // 按库存数量升序排列

        currentPage = 1;
        renderInventoryTable();

        if (filteredProducts.length === 0) {
            showNotification('没有低库存商品');
        } else {
            showNotification(`找到 ${filteredProducts.length} 个低库存商品`);
        }
    }

    // 打开添加模态框
    function openAddModal() {
        modalTitle.textContent = '添加产品';
        productForm.reset();
        productIdInput.value = '';
        modal.style.display = 'block';
    }

    // 打开编辑模态框
    function openEditModal(productId) {
        const product = allProducts.find(p => p.id === productId);
        if (product) {
            modalTitle.textContent = '编辑产品';
            productIdInput.value = product.id;
            productNameInput.value = product.name;
            productCategoryInput.value = product.category;
            productPriceInput.value = product.price;
            productQuantityInput.value = product.quantity;
            warehouseLocationInput.value = product.warehouseLocation;
            modal.style.display = 'block';
        }
    }

    // 打开库存调整模态框
    function openStockAdjustModal(productId) {
        const product = allProducts.find(p => p.id === productId);
        if (product) {
            adjustProductIdInput.value = product.id;
            currentStockInput.value = product.quantity;
            adjustQuantityInput.value = 1;
            adjustReasonInput.value = '';
            stockAdjustModal.style.display = 'block';
        }
    }

    // 保存产品
    function saveProduct() {
        const productData = {
            id: productIdInput.value ? parseInt(productIdInput.value) : generateNewId(),
            name: productNameInput.value,
            category: productCategoryInput.value,
            price: parseFloat(productPriceInput.value),
            quantity: parseInt(productQuantityInput.value),
            warehouseLocation: warehouseLocationInput.value,
            updatedAt: new Date().toISOString()
        };

        if (productIdInput.value) {
            // 更新现有产品
            const index = allProducts.findIndex(p => p.id === productData.id);
            if (index !== -1) {
                allProducts[index] = productData;
                showNotification('产品更新成功');
            }
        } else {
            // 添加新产品
            allProducts.push(productData);
            showNotification('产品添加成功');
        }

        // 保存前按ID升序排序
        allProducts.sort((a, b) => a.id - b.id);

        // 保存到本地存储
        saveProducts();

        // 更新过滤列表
        filteredProducts = [...allProducts];

        // 重新渲染
        currentPage = 1;
        renderInventoryTable();
        modal.style.display = 'none';
    }

    // 调整库存
    function adjustStock() {
        const productId = parseInt(adjustProductIdInput.value);
        const adjustType = adjustTypeInput.value;
        const adjustQuantity = parseInt(adjustQuantityInput.value);
        const adjustReason = adjustReasonInput.value;

        const productIndex = allProducts.findIndex(p => p.id === productId);
        if (productIndex !== -1) {
            let newQuantity;

            if (adjustType === 'increase') {
                newQuantity = allProducts[productIndex].quantity + adjustQuantity;
                showNotification(`成功入库 ${adjustQuantity} 个，库存已更新`);
            } else {
                // 检查库存是否足够
                if (allProducts[productIndex].quantity < adjustQuantity) {
                    showNotification('库存不足，无法完成出库操作');
                    return;
                }
                newQuantity = allProducts[productIndex].quantity - adjustQuantity;
                showNotification(`成功出库 ${adjustQuantity} 个，库存已更新`);
            }

            // 更新库存
            allProducts[productIndex] = {
                ...allProducts[productIndex],
                quantity: newQuantity,
                updatedAt: new Date().toISOString()
            };

            // 保存到本地存储
            saveProducts();

            // 更新过滤列表
            filteredProducts = [...allProducts];

            // 重新渲染
            renderInventoryTable();
            stockAdjustModal.style.display = 'none';
        }
    }

    // 生成新ID
    function generateNewId() {
        return allProducts.length > 0 ? Math.max(...allProducts.map(p => p.id)) + 1 : 1;
    }

    // 删除产品
    function deleteProduct(productId) {
        if (confirm('确定要删除这个产品吗？此操作不可恢复！')) {
            allProducts = allProducts.filter(p => p.id !== productId);
            // 删除后保持排序
            allProducts.sort((a, b) => a.id - b.id);
            saveProducts();

            // 更新过滤列表
            filteredProducts = [...allProducts];

            renderInventoryTable();
            showNotification('产品已删除');
        }
    }

    // 显示通知
    function showNotification(message) {
        notification.textContent = message;
        notification.style.display = 'block';

        setTimeout(() => {
            notification.style.display = 'none';
        }, 3000);
    }
}